﻿using Microsoft.EntityFrameworkCore;
using Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace DAL
{
    public class WhStockTakeDal
    {
        private readonly AppDbContext _dbContext;

        public WhStockTakeDal(AppDbContext dbContext)
        {
            _dbContext = dbContext;
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="data">实体</param>
        /// <returns>结果</returns>
        public async Task<int> CreateAsync(WhStockTake data)
        {
            _dbContext.WhStockTake.Add(data);
            return await _dbContext.SaveChangesAsync();
        }

        /// <summary>
        /// 根据ID查询
        /// </summary>
        /// <param name="Id">ID</param>
        /// <returns>盘点单</returns>
        public async Task<WhStockTake> GetByIdAsync(long Id)
        {
            return await _dbContext.WhStockTake.FirstOrDefaultAsync(g => g.InventoryOrderId == Id);
        }

        /// <summary>
        /// 查询所有
        /// </summary>
        /// <returns>盘点单列表</returns>
        public async Task<List<WhStockTake>> GetAllAsync()
        {
            return await _dbContext.WhStockTake.ToListAsync();
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="data">包含更新信息</param>
        public async Task<int> UpdateAsync(WhStockTake data)
        {
            _dbContext.WhStockTake.Update(data);
            return await _dbContext.SaveChangesAsync();
        }

        /// <summary>
        /// 根据ID删除
        /// </summary>
        /// <param name="Id">ID</param>
        public async Task<int> DeleteAsync(long Id)
        {
            var data = await GetByIdAsync(Id);
            if (data != null)
            {
                _dbContext.WhStockTake.Remove(data);
                return await _dbContext.SaveChangesAsync();
            }
            return 0;
        }

        /// <summary>
        /// 获取下一个盘点单号
        /// </summary>
        /// <returns>盘点单号</returns>
        public async Task<string> GetNextInventoryNoAsync()
        {
            string prefix = "PD" + DateTime.Now.ToString("yyyyMMdd");

            // 查询当天的最大单号
            var maxNo = await _dbContext.WhStockTake
                .Where(x => x.InventoryOrderNo.StartsWith(prefix))
                .OrderByDescending(x => x.InventoryOrderNo)
                .Select(x => x.InventoryOrderNo)
                .FirstOrDefaultAsync();

            int sequence = 1;
            if (!string.IsNullOrEmpty(maxNo) && maxNo.Length > prefix.Length)
            {
                string sequenceStr = maxNo.Substring(prefix.Length);
                if (int.TryParse(sequenceStr, out int lastSequence))
                {
                    sequence = lastSequence + 1;
                }
            }

            return prefix + sequence.ToString("D3"); // 3位序列号
        }


    }
}